#pragma once
#include<iostream>
#include<fstream>
#include<string>
#include<unordered_map>
#include"Log.hpp"
#include"InetAddr.hpp"
using namespace LogModule;
static std::string sep=": ";

class dict
{
public:
    dict(const std::string& path="./dictionary.txt")
    :_dict_path(path)
    {}
    bool Loaddict()
    {
        std::ifstream in(_dict_path);
        if(!in.is_open())
        {
            LOG(LogLevel::ERROR)<<"打开："<<_dict_path<<"错误";
            return false;
        }
        std::string line;
        while(std::getline(in,line))
        {
           auto pos=line.find(sep);
           if(pos==std::string::npos)
           {
             LOG(LogLevel::ERROR)<<"解析"<<line<<"失败";
             continue;
           }
           std::string english=line.substr(0,pos);
           std::string chinese=line.substr(pos+sep.size());
           if(chinese.empty()||english.empty())
           {
            LOG(LogLevel::WARNING)<<"没有有效内容";
            continue;
           }
           _dict.insert(std::make_pair(english,chinese));
           LOG(LogLevel::DEBUG)<<"加载"<<line;
        }
        
        in.close();
        return true;
    };
    std::string Translate(const std::string& word,InetAddr& client)
    {
        
        auto iter=_dict.find(word);
        if(iter==_dict.end())
        {
            return "None";
        }
        LOG(LogLevel::DEBUG)<<"进入到了翻译模块"<<"["<<client.Ip()<<":"<<client.Port()<<"]"<<"正在发送请求";
        return iter->second;
    };
    ~dict()
    {}

private:
    std::unordered_map<std::string,std::string> _dict;
    std::string _dict_path;
};